<?php

namespace app\admin\model;

use app\common\enums\StatusEnum;

class UserRole extends \app\common\model\UserRole
{
    /**
     * 获取角色对应的用户
     * @param $roleId
     * @return array
     */
    public static function getColumnByRole($roleId)
    {
        return static::field('user_id, role_id')->where(['role_id' => $roleId])->column('role_id', 'user_id');
    }

    /**
     * 获取用户对应的角色
     * @param $userId
     * @return array
     */
    public static function getColumnByUser($userId)
    {
        return static::field('user_id, role_id')->where(['user_id' => $userId])->column('user_id', 'role_id');
    }

    public static function getColumn($userIds)
    {
        $sql = static::field('ur.user_id, r.name')
            ->alias('ur')
            ->join('role r', 'ur.role_id = r.id', 'INNER')
            ->where(['r.status' => StatusEnum::ENABLED]);
        if ($userIds) {
            $sql->where('ur.user_id', 'in', $userIds);
        }
        $model = $sql->select()->toArray();
        $result = [];
        foreach ($model as $key => $value) {
            $result[$value['user_id']][] = $value['name'];
        }
        foreach ($result as $userId => $value) {
            $result[$userId] = implode(',', $value);
        }

        return $result;
    }
}